<?php

namespace app\stores\logic\order;

use app\beautiful\logic\FreightLogic;


use app\beautiful\model\goods\GoodsGroupModel;
use app\beautiful\model\goods\GoodsOtherSkuDetailModel;
use app\beautiful\model\mall\GoodsCategoryModel;
use app\beautiful\model\order\OrderGoodsGroupDetailModel;
use app\beautiful\model\mall\GoodsModel;

use app\beautiful\model\mall\GoodsSkuModel;

use app\beautiful\model\member\MemberCouponModel;

use app\beautiful\model\order\GoodsOrderItemModel;

use app\beautiful\model\order\GoodsOrderModel;

use app\beautiful\model\order\OrderGoodsGroupModel;

use app\beautiful\model\order\OrderGoodsModel;
use app\beautiful\model\setting\SettingBalanceModel;

use app\beautiful\model\setting\SettingIntegralModel;
use app\stores\model\promotion\ActivityModel;
use app\stores\model\promotion\TeamActivityModel;


class OrderSetMealLogic{

    use OrderTrait;

    protected $goods_data=[];

    protected $total_price=0;

    protected $member_coupon_id;

    protected $sku_datas=[];

    protected $order_item_data=[];


    protected $order_goods_group_detail=[];

    protected $num;

    protected $all_goods_gross;

    protected $p_mid;

    protected $ta_id;

    protected $activity_title;

    protected $activity_price;

    public function createOrder($params)

    {
        //判断用户

        empty($params['member_id']) && $this->error('请先登录后再操作');

        $this->checkMember($params['member_id'], false);


        //地推
        $this->p_mid = isset($params['p_mid'])?$params['p_mid']:0;
        $this->ta_id = isset($params['team_activity_id'])?$params['team_activity_id']:0;

        //判断商品

        if(empty($params['goods']) || !is_array($params))  $this->error('请选择商品');


        foreach ($params['goods'] as $k => $v){

            $this->checkGoods($v,false);
        }

        if(empty($params['total_price'])) $this->error('参数错误#1');

        //判断优惠卷

        $coupon_id = $params['coupon_id'] ?? 0;

        $couponBalance = 0;

        if(!empty($coupon_id)){

            if(null === $myCoupon =  MemberCouponModel::find($coupon_id)) $this->error('优惠券不存在');

            if($myCoupon->status == 1 || $myCoupon->money_limit > $this->total_price) $this->error('该优惠券不可用');

            if($myCoupon->member_id != $params['member_id'])  $this->error('该优惠券不可用');

            $couponBalance = $myCoupon->coupon_money;

        }

        //判断积分抵扣

        $use_integral=(int)$params['use_integral'];

        if($use_integral==1){

            $integral_balance=$this->getIntegralBalance($this->total_price);

        }

        $integral=isset($integral_balance) ? $integral_balance['integral'] : 0;

        $balance=isset($integral_balance) ? $integral_balance['balance'] : 0;

        //获取邮费

        $freight = 0;

        //获取需要支付的金额

        $need_pay=round((($this->total_price)*100 + $freight*100 - $couponBalance*100 - $balance*100)/100,2);

        //判断支付方式
        $return = checkPayWay($params,$need_pay,$this->member->member_id,$this->shopId);

        if($return['error']){
            $this->error($return['error']);
        }else{
            $mix_pay_money = $return['mix_pay_money'];
        }


        //判断总价
        //if((float)$params['total_price'] != $this->total_price) $this->error('参数错误#2');

        if((float)$params['total_price'] != $need_pay) $this->error('参数错误#2');
        //保存订单

        $order = new GoodsOrderModel();

        $order_data=[

            'shop_id'=>$this->shopId,

            'order_type'=>'set_meal',

            'member_id'=>$params['member_id'],

            'total_price'=>$this->total_price,

            'need_pay'=>$need_pay,

            'freight'=>$freight,

            'member_coupon_id'=>$params['coupon_id'],

            'coupon_money'=>$couponBalance,

            'use_integral'=>isset($integral_balance) ? $integral_balance['integral'] : 0,

            'integral_balance'=>isset($integral_balance) ? $integral_balance['balance'] : 0,

            'is_paid'=>0,

            'status'=>1,

            'from_type'=>$params['from_type'],

            'all_goods_gross'=>$this->all_goods_gross,

            'mix_pay_type'=>(isset($mix_pay_money) && $mix_pay_money)?implode(',',array_keys($mix_pay_money)):null,

            'platform_money'=>isset($mix_pay_money['platform_money'])?$mix_pay_money['platform_money']:0,

            'money'=>isset($mix_pay_money['money'])?$mix_pay_money['money']:0,

            'weixin'=>isset($mix_pay_money['weixin'])?$mix_pay_money['weixin']:0
        ];

        if(isset($params['order_type']) && $params['order_type'] == 'promotion'){

            $order_data['team_commission'] = $params['team_commission'];

            $order_data['team_activity_id'] = $params['team_activity_id'];

            $order_data['team_id'] = $params['team_id'];

            $order_data['p_mid'] = $params['p_mid'];

            $order_data['activity_title'] = $this->activity_title;

            $order_data['activity_price'] = $this->activity_price;
        }

        $order->save($order_data);

        GoodsOrderModel::where(['order_id'=>$order->order_id])->save(['order_sn'=>createOrderSn($order->order_id,1)]);
        //保存订单商品
        foreach ($this->order_item_data as $k => $v){

            $this->order_item_data[$k]['order_id']=$order->order_id;

        }
        $order_item_model= new GoodsOrderItemModel();

        $order_item_model->saveAll($this->order_item_data);

        //创建订单套餐分组和分组详情
        $item = GoodsOrderItemModel::with(['goods'=>function($query){
            $query->where(['is_delete'=>0]);
        }])->where(['order_id'=>$order->order_id])->select()->toArray();

        foreach($item as $k=>$v){
            $this->goodsGroup($v['goods'],$order->order_id,$v['order_item_id']);
            $this->goods($v['goods'],$order->order_id,$v['order_item_id']);

        }
        //套餐订单分组详情
        $order_group_detail = new OrderGoodsGroupDetailModel();
        $order_group_detail->saveAll($this->order_goods_group_detail);


        //保存商品
        $goods_model=new GoodsModel();

        $goods_model->saveAll($this->goods_data);

        //保存商品规格

        $goods_sku_model = new GoodsSkuModel();

        $goods_sku_model->saveAll($this->sku_datas);


        return $order->order_id;

    }




    public function cancelOrder($params)

    {

        $this->checkMember($params['member_id'],false);

        $this->checkOrder($params['order_id'],true);



        if($this->order->order_type != 'set_meal') $this->error('订单不存在');

        if($this->order->is_delete != 0) $this->error('订单不存在');

        if($this->order->is_paid == 1 || $this->order->status != 1) $this->error('订单无法取消');



        $this->order->status=-1;

        $this->order->save();



        $this->cancelGoods();



        //保存商品

        $goods_model=new GoodsModel();

        $goods_model->saveAll($this->goods_data);



        //保存商品规格

        $goods_sku_model = new GoodsSkuModel();

        $goods_sku_model->saveAll($this->sku_datas);



        return true;

    }



    public function createFakeOrder($params)

    {

        //判断用户

        empty($params['member_id']) && $this->error('请先登录后再操作');

        $this->checkMember($params['member_id'], false);



        //判断商品

        if(empty($params['goods']) || !is_array($params))  $this->error('请选择商品');

        foreach ($params['goods'] as $k => $v){

            $this->checkGoods($v,false);

        }





        //判断配送方式

        if( empty($params['logistics_type']) || !in_array($params['logistics_type'],[1,2])) $this->error('请选择配送方式');

        //快速配送判断邮寄地址

        if($params['logistics_type']==1){

            empty($params['receiving_name']) && $this->error('请输入收货人');

            if(empty($params['receiving_mobile']) || (!is_mobile($params['receiving_mobile']) && !is_phone($params['receiving_mobile'])) )  $this->error('请输入收货人手机号');

            empty($params['receiving_address_province']) && $this->error('请输入收货省份');

            empty($params['receiving_address_city']) && $this->error('请输入收货城市');

            empty($params['receiving_address_county']) && $this->error('请输入收货城镇');

            empty($params['receiving_address_info']) && $this->error('请输入收货具体地址');

        }



        //判断总价

        if(empty($params['total_price'])) $this->error('参数错误#1');

        if((float)$params['total_price'] != $this->total_price) $this->error('参数错误#2');





        //获取邮费

        $freight = 0;

        if($params['logistics_type']==1){

            $province= empty($params['receiving_address_province']) ? '' : $params['receiving_address_province'];

            $freight_logic= new FreightLogic($this->shopId);

            $freight=$freight_logic->getFreightPrice($province,$this->num);

            if($freight==-1) $this->error('收货地址暂不支持发货');

        }



        //获取需要支付的金额

        $need_pay=$params['need_pay'];





        //保存订单

        $order = new GoodsOrderModel();

        $order_data=[

            'shop_id'=>$this->shopId,

            'order_type'=>'normal',

            'logistics_type'=>$params['logistics_type'],

            'member_id'=>$params['member_id'],

            'total_price'=>$this->total_price,

            'need_pay'=>$need_pay,

            'freight'=>$freight,

            'is_paid'=>1,

            'pay_time'=>time(),

            'pay_type'=>'offline',

            'status'=>$params['status'],

        ];

        if($params['logistics_type']==1){

            $order_data['receiving_name']=$params['receiving_name'];

            $order_data['receiving_mobile']=$params['receiving_mobile'];

            $order_data['receiving_address_province']=$params['receiving_address_province'];

            $order_data['receiving_address_city']=$params['receiving_address_city'];

            $order_data['receiving_address_county']=$params['receiving_address_county'];

            $order_data['receiving_address_info']=$params['receiving_address_info'];

        }

        $youhui_balance=round((($this->total_price)*100 + $freight*100 - $need_pay*100) /100,2);

        if($youhui_balance>0){

            $order_data['youhui_balance']=$youhui_balance;

        }

        $order->save($order_data);



        //保存订单商品

        foreach ($this->order_item_data as $k => $v){

            $this->order_item_data[$k]['order_id']=$order->order_id;

        }

        $order_item_model= new GoodsOrderItemModel();

        $order_item_model->saveAll($this->order_item_data);



        //保存商品

        $goods_model=new GoodsModel();

        $goods_model->saveAll($this->goods_data);



        //保存商品规格

        $goods_sku_model = new GoodsSkuModel();

        $goods_sku_model->saveAll($this->sku_datas);



        return $order->order_id;

    }



    public function getIntegralBalance($total_price)

    {

        $SettingBalance = SettingBalanceModel::where([['shop_id','=', $this->shopId]])->find();

        if(null === $SettingBalance){

            $integral_deduction_balance_limit_rate = 0;

        }else{

            $integral_deduction_balance_limit_rate = $SettingBalance->integral_deduction_balance_limit_rate; //积分抵扣的比率 百分比

        }

        $integralSetting = SettingIntegralModel::where([['shop_id','=', $this->shopId]])->find();

        if($integralSetting === null){ //如果是空 代表不使用积分抵扣余额

            $integral_exchange_balance = 0;

        }else{

            $integral_exchange_balance = $integralSetting->integral_exchange_balance;//汇率

        }



        $pre_can_exchange_balance=round(($total_price*($integral_deduction_balance_limit_rate*100))/10000,2);

        $pre_can_exchange_integral=$integral_exchange_balance==0 ? 0 : round(($pre_can_exchange_balance*10000)/($integral_exchange_balance*100),0);

        $member_integral=$this->member->integral;

        if($member_integral>=$pre_can_exchange_integral){

            $return=[

                'integral'=>$pre_can_exchange_integral,

                'balance'=>$pre_can_exchange_balance

            ];

        }else{

            $return=[

                'integral'=>$member_integral,

                'balance'=>round(($member_integral*($integral_exchange_balance*100))/10000,2),

            ];

        }

        return $return;



    }



    public function checkGoods($datas,$lock)

    {

        empty($datas['goods_id']) && $this->error('参数错误#3');

        empty($datas['num']) && $this->error('参数错误#4');

        $this->num = ($this->num ?? 0) + $datas['num'];



        $goods=GoodsModel::where([

            ['shop_id','=',$this->shopId],

            ['status','=',1],

            ['is_delete','=',0],

            ['type','=',3],

            ['goods_id','=',$datas['goods_id']]

        ])->field('origin_type,type,shop_id,category_id,goods_id,name,cover_img,original_price,total_value,vip_price,quota,gross,take_count,fictitious_take_count,is_have_sku,vip_discount_type,discount_detail')

            ->lock($lock)->json(['discount_detail'],true)->find($datas['goods_id']);

        empty($goods) && $this->error('套餐不存在');

        //地推
        if($this->ta_id>0){
            $team_activity = TeamActivityModel::where(['team_activity_id'=>$this->ta_id,'status'=>1,'is_delete'=>0])->find();
            if(empty($team_activity)) $this->error('推广活动不存在');
            $activity = ActivityModel::where(['activity_id'=>$team_activity->activity_id,'status'=>1,'is_delete'=>0])->find();
            if(empty($activity)) $this->error('推广活动不存在');
            if($activity){
                $goods->quota = $activity->quota;
                $this->activity_title = $activity->title;
                $this->activity_price = $activity->price;
            }
        }

        if($goods->quota < $datas['num']) $this->error ('套餐库存不足');

        $goods->price = $goods->original_price;

//        $goods_price = $this->vipPrice($goods,$this->member);
        $return = getMemberPrice($this->member,$this->shopId,$goods,$goods['total_value'],$goods['type'],$this->p_mid,$this->ta_id);

        $discount_detail = $goods->discount_detail;
        $level_id = getMemberLevel($this->member->member_id,$this->shopId);
        $discount = getMemberDiscount($this->member,$this->shopId,$goods->vip_discount_type,$discount_detail);

        //分类
        $category = GoodsCategoryModel::where(['shop_id'=>$goods['shop_id'],'category_id'=>$goods['category_id'],'is_delete'=>0])->find();

        //处理订单商品表

        $this->order_item_data[]=[

            'shop_id'=>$this->shopId,

            'goods_id'=>$datas['goods_id'],

            'goods_type'=>'set_meal',

            'category_name'=>$category?$category->name:null,

            'goods_name'=>$goods->name,

            'goods_cover_img'=>$goods->cover_img,

            'goods_gross'=>$goods->gross,

            'goods_sku_name'=>isset($sku) ? $sku->name : '',

            'goods_original_price'=>isset($sku) ? $sku->original_price : $goods->original_price,

            'goods_price'=>$return['price'],

            'goods_num'=>$datas['num'],

            'remain_num'=>$datas['num'],

            'type'=>3,

            'vip_discount_type'=>$level_id>0?$goods->vip_discount_type:0,

            'discount_detail'=>$level_id>0?$discount:0

        ];

        $this->all_goods_gross += $goods->gross;

        //$price = $this->member->level_id ==0 ? $goods->original_price : $goods->price;

        $price = $return?$return['price']:$goods->original_price;

        $this->total_price = round((($this->total_price)*100+$price*$datas['num']*100)/100,2);



        //处理商品表
        $goods=$goods->toArray();
        //地推
        if($this->ta_id>0){
            //加数量
            $sales_num = $activity['sales_num'] + $datas['num'];
            //减库存
            $quota = $activity['quota'] - $datas['num'];
            ActivityModel::up(['sales_num'=>$sales_num],['activity_id'=>$team_activity->activity_id]);
            ActivityModel::up(['quota'=>$quota],['activity_id'=>$team_activity->activity_id]);

        }else{
            $goods['quota']=$goods['quota']-$datas['num'];

            $goods['take_count']=$goods['take_count']+$datas['num'];

            $goods['fictitious_take_count']=$goods['fictitious_take_count']+$datas['num'];
        }

        unset($goods['discount_detail']);
        $this->goods_data[]=$goods;




    }


    protected function goodsGroup($datas,$order_id,$order_item_id){
        empty($datas['goods_id']) && $this->error('参数错误#');

        $goods_group = GoodsGroupModel::with(['groupDetail'=>function($query){
            $query->with(['goods'=>function($query){
                $query->where(['is_delete'=>0]);
            }])->where(['is_delete'=>0]);
        }])->where([
            ['shop_id','=',$this->shopId],
            ['is_delete','=',0],
            ['goods_id','=',$datas['goods_id']]
        ])->field('*')
            ->select()->toArray();
        if($goods_group){
            $group_model = new OrderGoodsGroupModel();
            foreach ($goods_group as $k=>$v){
                $order_goods_group = [
                    'shop_id' => $v['shop_id'],
                    'order_id'=>$order_id,
                    'order_item_id'=>$order_item_id,
                    'goods_id' => $v['goods_id'],
                    'group_name' => $v['group_name'],
                    'type' => $v['type'],
                    'num' => $v['num'],
                    'choose_num' => $v['choose_num'],
                    'is_choose_same' => $v['is_choose_same']
                ];
                $order_goods_group_id = $group_model->insertGetId($order_goods_group);

                $this->goodGroupDetail($v['groupDetail'],$order_goods_group_id,$order_id,$order_item_id);

                $this->order_goods_group_id[] = $order_goods_group_id;
            }

        }


    }

    protected function goodGroupDetail($datas,$order_goods_group_id,$order_id,$order_item_id){
        if($datas){

            foreach ($datas as $k=>$v){
                $detail['shop_id'] = $v['shop_id'];
                $detail['order_id'] = $order_id;
                $detail['order_item_id'] = $order_item_id;
                $detail['order_goods_group_id'] = $order_goods_group_id;
                $detail['num'] = $v['num'];
                $detail['use_condition'] = $v['use_condition'];
                $detail['once_limit_num'] = $v['once_limit_num'];
                $detail['end_type'] = $v['end_type'];
                $detail['end_time_num'] = $v['end_time_num'];
                $detail['end_time_type'] = $v['end_time_type'];
                $detail['sort'] = $v['sort'];
                $detail['remain_num'] = $v['num'];
                $detail['goods_group_detail_id'] = $v['goods_group_detail_id'];
                if($v['goods_id']){
                    $unit = GoodsOtherSkuDetailModel::where(['is_delete'=>0,'other_sku_detail_id'=>$v['goods']['unit_id']])->find();
                    $sku = GoodsSkuModel::where(['goods_id'=>$v['goods_id'],'sku_id'=>$v['sku_id'],'is_delete'=>0])->find();
                    $detail['goods_id'] = $v['goods_id'];
                    $detail['goods_name'] = $v['goods']['name'];
                    $detail['goods_original_price'] = $v['goods']['original_price'];
                    $detail['unit'] = $unit?$unit->group_detail_name:'';
                    $detail['sku_name'] = $sku?$sku->name:null;

                }else{
                    $detail['goods_name'] = $v['goods_name'];
                    $detail['goods_original_price'] = $v['original_price'];
                    $detail['unit'] = $v['unit_name'];
                }
                $this->order_goods_group_detail[] = $detail;
            }

        }

    }

    /*订单产品信息记录*/
    protected function goods($datas,$order_id,$order_item_id){
        $order_goods = [
            'goods_id'=>$datas['goods_id'],
            'order_id'=>$order_id,
            'order_item_id'=>$order_item_id,
            'use_type'=>$datas['use_type'],
            'use_time_type'=>$datas['use_time_type'],
            'use_time_num'=>$datas['use_time_num'],
            'use_start_time'=>$datas['use_start_time'],
            'use_end_time'=>$datas['use_end_time'],
            'use_limit'=>$datas['use_limit'],
            'use_limit_detail'=>$datas['use_limit_detail'],
            'is_limit_buy'=>$datas['is_limit_buy'],
            'can_buy_type'=>$datas['can_buy_type'],
            'can_buy_num'=>$datas['can_buy_num'],
            'total_value'=>$datas['total_value'],
            'is_need_appointment'=>$datas['is_need_appointment'],
            'appointment_explain'=>$datas['appointment_explain'],
            'purchase_information'=>$datas['purchase_information'],
            'remarks'=>$datas['remarks'],
            'weight'=>$datas['weight'],
            'type'=>$datas['type'],
        ];

        $order_goods_model =new OrderGoodsModel();
        $order_goods_model->save($order_goods);
    }

    protected function cancelGoods()

    {

        $order_item_data=GoodsOrderItemModel::where([

            ['shop_id','=',$this->shopId],

            ['order_id','=',$this->order->order_id],

            ['goods_type','=','normal']

        ])->field('goods_id,goods_sku_id,goods_num')->select()->toArray();

        $goods_ids=[];$sku_ids=[];$order_item_array=[];



        if(!empty($order_item_data)){

            foreach ($order_item_data as $k => $v){

                $goods_ids[]=$v['goods_id'];

                $sku_ids[]=$v['goods_sku_id'];

                $order_item_array['goods'][$v['goods_id']]=$v;

                $order_item_array['sku'][$v['goods_sku_id']]=$v;

            }

        }



        //处理商品

        $goods_data=GoodsModel::where([

            ['shop_id','=',$this->shopId],

            ['goods_id','in',$goods_ids]

        ])->field('goods_id,quota,take_count,fictitious_take_count')->select()->toArray();



        foreach ($goods_data as $k => $v){

            $num=$order_item_array['goods'][$v['goods_id']]['goods_num'] ?? 0;

            $goods_data[$k]['quota']=$v['quota'] +$num;

            $goods_data[$k]['fictitious_take_count']=($v['fictitious_take_count'] -$num) <=0 ? $v['fictitious_take_count'] : ($v['fictitious_take_count'] -$num);

            $goods_data[$k]['take_count']=$v['take_count'] -$num;

        }

        $this->goods_data=$goods_data;



        //处理规格

        $sku_datas=GoodsSkuModel::where([

            ['shop_id','=',$this->shopId],

            ['sku_id','in',$sku_ids],

        ])->field('sku_id,quota,take_count')->select()->toArray();



        foreach ($sku_datas as $k => $v){

            $num=$order_item_array['sku'][$v['sku_id']]['goods_num'] ?? 0;

            $sku_datas[$k]['quota']=$v['quota'] +$num;

            $sku_datas[$k]['take_count']=$v['take_count'] -$num;

        }

        $this->sku_datas=$sku_datas;







    }

    protected function vipPrice($goods,$member){
        if($goods->discount_detail){
            $discount_detail = $goods->discount_detail;
            for ($i=0;$i<count($discount_detail);$i++){
                if($discount_detail[$i]['level_id']==$member->level_id){
                    if($goods->vip_discount_type==1){
                        $goods->price = $goods->original_price*($discount_detail[$i]['member_price']/10);
                    }
                    if($goods->vip_discount_type==2){
                        $goods->price = $discount_detail[$i]['bid_price'];
                    }
                    if($goods->vip_discount_type==3){
                        $goods->price = $goods->original_price-$discount_detail[$i]['reduce_price'];
                    }
                }
            }
        }

        return $goods->price;
    }

}